//
// Created by bourne on 2024/4/22.
//
#include <iostream>
#include <list>

int main() {
  std::list<int> myList = {1, 2, 3, 4, 5};

  std::cout << "Initial list: ";
  for (int num : myList) {
    std::cout << num << " ";
  }
  std::cout << std::endl;

  // 在list的开头添加一个元素
  myList.push_front(0);
  std::cout << "After push_front(0): ";
  for (int num : myList) {
    std::cout << num << " ";
  }
  std::cout << std::endl;

  // 在list的末尾添加一个元素
  myList.push_back(6);
  std::cout << "After push_back(6): ";
  for (int num : myList) {
    std::cout << num << " ";
  }
  std::cout << std::endl;

  // 删除第一个元素
  myList.pop_front();
  std::cout << "After pop_front(): ";
  for (int num : myList) {
    std::cout << num << " ";
  }
  std::cout << std::endl;

  // 删除最后一个元素
  myList.pop_back();
  std::cout << "After pop_back(): ";
  for (int num : myList) {
    std::cout << num << " ";
  }
  std::cout << std::endl;

  // 清除整个 list
  myList.clear();
  std::cout << "After clear(): ";
  for (int num : myList) {
    std::cout << num << " ";
  }
  std::cout << std::endl;

  // 重新添加元素并排序
  myList = {1, 2, 3, 4, 100};
  myList.sort();
  std::cout << "Sorted list: ";
  for (int num : myList) {
    std::cout << num << " ";
  }
  std::cout << std::endl;

  // 合并另一个list
  std::list<int> anotherList = {10, 9, 8, 7};
  myList.merge(anotherList);
  std::cout << "Merged list: ";
  for (int num : myList) {
    std::cout << num << " ";
  }
  std::cout << std::endl;

  // 移除重复元素
  myList.unique();
  std::cout << "Unique elements: ";
  for (int num : myList) {
    std::cout << num << " ";
  }
  std::cout << std::endl;

  // 反转 list
  myList.reverse();
  std::cout << "Reversed list: ";
  for (int num : myList) {
    std::cout << num << " ";
  }
  std::cout << std::endl;

  std::cout << "================" << std::endl;

  std::list<int> myList2 = {1, 2, 3, 4, 5};

  // 使用迭代器遍历list
  for (std::list<int>::iterator iter = myList2.begin(); iter != myList2.end(); ++iter) {
    std::cout << *iter << " ";
  }
  std::cout << std::endl;

  // 使用auto简化迭代器类型
  for (auto iter = myList2.begin(); iter != myList2.end(); ) {
    std::cout << *iter << " ";
    ++iter;
  }
  std::cout << std::endl;

  // 使用基于范围的for循环（C++11及以上）
  for (const auto& value : myList2) {
    std::cout << value << " ";
  }
  std::cout << std::endl;

  // 改变list中的值
  for (auto iter = myList2.begin(); iter != myList2.end(); ++iter) {
    *iter += 10; // 将每个元素的值增加10
  }

  // 再次打印修改后的list
  for (const auto& value : myList2) {
    std::cout << value << " ";
  }
  std::cout << std::endl;

  // 计算list中元素的数量
  std::list<int>::iterator iter = myList2.begin();
  std::cout << "The size of the list is: " << std::distance(iter, myList2.end()) << std::endl;
  std::cout << myList2.size() << std::endl;

  return 0;
}
